﻿#include "LoginDialog.h"
#include <QMessageBox>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QDebug>
#include <QCryptographicHash>
#include <QHeaderView>
#include <QComboBox>
#include <QTableWidgetItem>
#include <QFile>
#include <QCoreApplication>
#include <QDebug>

WorkerLevel LoginDialog::CurrentLevel = WorkerLevel::WL_GUEST;

#pragma execution_character_set("utf-8")
LoginDialog::LoginDialog(WorkMode wm,DialogType dt, QWidget *parent) : QDialog(parent)
  ,m_wm(wm)
  ,m_dt(dt)
{
    this->setAttribute(Qt::WA_TranslucentBackground, true);
    qRegisterMetaType<QJsonArray>("QJsonArray");
    qRegisterMetaType<QJsonObject>("QJsonObject");
    qRegisterMetaType<UserOptID>("UserOptID");
    setFocusPolicy(Qt::StrongFocus);
    setupUI();
    initUserWorker();

}
LoginDialog::~LoginDialog()
{
    emit sglClose();
}


void LoginDialog::closeEvent(QCloseEvent *event)
{
    emit sglClose();
}
//void LoginDialog::setWorkMode(int workType)
//{
//    switch (workType){
//    case 0:
//        pbtnUserManage->setVisible(true);
//        this->resize(600,350);
//        break;
//    case 1:
//        pbtnUserManage->setVisible(false);
//        this->resize(300,300);
//        break;
//    }
//}

//WorkerLevel LoginDialog::getLoginLevel()
//{
//   return m_level;
//}
QString LoginDialog::getLoginWorkerID()
{
   return m_workID;
}
QString LoginDialog::getLoginWorkerName()
{
   return m_name;
}

void LoginDialog::initUserWorker()
{
    pUserWorkerThread = new QThread();
    pUserWorkerThread->setObjectName("UserWokerThread");

    pUserWorker = new UserWorker;
    pUserWorker->moveToThread(pUserWorkerThread);

    connect(this, &LoginDialog::sglClose, pUserWorker, &UserWorker::deleteLater);
    connect(pUserWorker, &QObject::destroyed, pUserWorkerThread, &QThread::quit);
    connect(pUserWorkerThread, &QThread::finished, pUserWorkerThread, &QThread::deleteLater);
    connect(pUserWorkerThread, &QThread::started, pUserWorker, &UserWorker::onInit);

    connect(this,&LoginDialog::sglOperate,pUserWorker,&UserWorker::onOperate);
    connect(pUserWorker,&UserWorker::sglOperateResult,this,&LoginDialog::onOperateResult);
    connect(pUserWorker,&UserWorker::sglAllUser,this,&LoginDialog::onAllUserShow);
    connect(this, &LoginDialog::sglLoginSucceed, this, &QDialog::accept);
    pUserWorkerThread->start();
}
void LoginDialog::setupUI()
{
    this->resize(600,350);
    //setWindowTitle(tr("登录"));
    setWindowFlags (Qt::Widget | Qt::FramelessWindowHint);
    QVBoxLayout *vlayout = new QVBoxLayout();
    this->setLayout(vlayout);
    vlayout->setMargin(0);
    stkwgt = new QStackedWidget(this);
    stkwgt->setObjectName("stkwgtLogin");
    vlayout->addWidget(stkwgt);

    //第一个页面
    {
        QWidget *wgtFirst = new QWidget();
        QVBoxLayout *vLayout0 = new QVBoxLayout();
        QVBoxLayout *vLayout1 = new QVBoxLayout();
        QHBoxLayout *hLayout0 = new QHBoxLayout();
        QHBoxLayout *hLayout1 = new QHBoxLayout();
        QHBoxLayout *hLayout2 = new QHBoxLayout();


        QLabel* lblWorkerNum = new QLabel("");
        lblWorkerNum->setObjectName("lblWorkerNum");
        //lblWorkerNum->setPixmap(QPixmap("resources/qss/login/username.png").scaled(20,20));
        QLabel* lblPassword = new QLabel("");
        lblPassword->setObjectName("lblPassword");
        //lblPassword->setPixmap(QPixmap("resources/qss/login/password.png").scaled(20,20));

        //如果显示器为触摸模式DT_PAD：QLineEdit 将会提升为：QLineEdit调用数字键盘
        if(m_dt == DialogType::DT_PAD){
            ledtWorkerID = new QLineEdit();
            ledtPassword = new QLineEdit();
        }else{  //如果显示器为PC模式则使用键盘鼠标
            ledtWorkerID = new QLineEdit;
            ledtPassword = new QLineEdit;
        }

        ledtWorkerID->setPlaceholderText(tr("请输入工号"));
        ledtPassword->setPlaceholderText(tr("请输入密码"));

        pbtnLogin = new QPushButton(tr("登录"));
        pbtnUserManage = new QPushButton(tr("进入用户管理"));
        pbtnCancel = new QPushButton(tr("退出"));


        lblWorkerNum->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
        lblPassword->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
        ledtWorkerID->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
        ledtPassword->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
        pbtnLogin->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
        pbtnUserManage->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
        pbtnCancel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

        hLayout1->addWidget(lblWorkerNum);
        hLayout1->addWidget(ledtWorkerID);
        hLayout2->addWidget(lblPassword);
        hLayout2->addWidget(ledtPassword);
        vLayout1->addLayout(hLayout1);
        vLayout1->addLayout(hLayout2);
        vLayout1->addWidget(pbtnLogin);
        vLayout1->addWidget(pbtnUserManage);
        vLayout1->addWidget(pbtnCancel);
        hLayout0->addStretch();
        hLayout0->addLayout(vLayout1);
        hLayout0->addStretch();
        vLayout0->addStretch();
        vLayout0->addLayout(hLayout0);
        vLayout0->addStretch();
        wgtFirst->setLayout(vLayout0);
        stkwgt->addWidget(wgtFirst);
    }

    //第二个页面
    {
        QWidget *wgtSecond = new QWidget();
        QLabel *label1 = new QLabel(tr("用户ID:"));
        lblWorkerID = new QLabel("");
        QLabel *label2 = new QLabel(tr("用户名:"));
        lblWorkerName = new QLabel("");
        QLabel *label3 = new QLabel(tr("用户权级:"));
        lblWorkerLevel = new QLabel("");
        pbtnLogout = new QPushButton(tr("返回登录"));
        tblwgtWorkerData = new QTableWidget();
        tblwgtWorkerData->setObjectName("tblUser");
        pbtnModifyPassword = new QPushButton(tr("修改密码"));
        pbtnModifyInfo = new QPushButton(tr("修改信息"));
        pbtnRegister = new QPushButton(tr("注册用户"));
        pbtnDelete = new QPushButton(tr("删除用户"));

        lblWorkerID->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
        lblWorkerName->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
        lblWorkerLevel->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
        pbtnLogout->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
        pbtnModifyPassword->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
        pbtnModifyInfo->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
        pbtnRegister->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
        pbtnDelete->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
        tblwgtWorkerData->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);

        ledtPassword->setEchoMode(QLineEdit::Password);
        ledtWorkerID->setFocus();

        tblwgtWorkerData->insertColumn(tblwgtWorkerData->columnCount());
        tblwgtWorkerData->insertColumn(tblwgtWorkerData->columnCount());
        tblwgtWorkerData->insertColumn(tblwgtWorkerData->columnCount());
        QStringList hHeaderList = {tr("用户ID"),tr("用户名"),tr("用户权级")};
        tblwgtWorkerData->setHorizontalHeaderLabels(hHeaderList);


        QHBoxLayout *hLayout = new QHBoxLayout();
        QVBoxLayout *vLayout = new QVBoxLayout();
        QVBoxLayout *vLayout0 = new QVBoxLayout();
        QVBoxLayout *vLayout1 = new QVBoxLayout();
        QHBoxLayout *hLayout0 = new QHBoxLayout();
        QFormLayout *fLayout = new QFormLayout();

        fLayout->addRow(label1,lblWorkerID);
        fLayout->addRow(label2,lblWorkerName);
        fLayout->addRow(label3,lblWorkerLevel);

        vLayout1->addWidget(pbtnLogout);
        vLayout1->addWidget(pbtnModifyInfo);
        vLayout1->addWidget(pbtnModifyPassword);
        vLayout1->addWidget(pbtnRegister);
        vLayout1->addWidget(pbtnDelete);

        vLayout0->addLayout(fLayout);
        vLayout0->addWidget(tblwgtWorkerData);

        hLayout->addLayout(vLayout0);
        hLayout->addLayout(vLayout1);

        //hLayout0->addStretch();
        hLayout0->addLayout(hLayout);
        //hLayout0->addStretch();
        //vLayout->addStretch();
        vLayout->addLayout(hLayout0);
        //vLayout->addStretch();
        wgtSecond->setLayout(vLayout);
        stkwgt->addWidget(wgtSecond);
    }

    connect(pbtnCancel, &QPushButton::clicked, this, &LoginDialog::on_pbtnCancel_clicked);
    connect(pbtnLogin, &QPushButton::clicked, this, &LoginDialog::on_pbtnLogin_clicked);
    connect(pbtnUserManage, &QPushButton::clicked, this, &LoginDialog::on_pbtnUserManage_clicked);
    connect(pbtnLogout, &QPushButton::clicked, this, &LoginDialog::on_pbtnLogout_clicked);
    connect(pbtnRegister, &QPushButton::clicked, this, &LoginDialog::on_pbtnRegister_clicked);
    connect(pbtnModifyPassword, &QPushButton::clicked, this, &LoginDialog::on_pbtnModifyPassword_clicked);
    connect(pbtnModifyInfo, &QPushButton::clicked, this, &LoginDialog::on_pbtnModifyInfo_clicked);
    connect(pbtnDelete, &QPushButton::clicked, this, &LoginDialog::on_pbtnDelete_clicked);
    //设置登录页面的qss: 样式以迁至resources\qss\login\Login.qss文件内
    setPageStyle();

    {//工作模式
        switch (m_wm){
        case WorkMode::WM_LOGIN:
            pbtnUserManage->setVisible(false);
            this->resize(300,300);
            break;
        case WorkMode::WM_MANAGE:
            pbtnUserManage->setVisible(true);
            this->resize(600,350);
            break;
        }
    }
}
void LoginDialog::setPageStyle()
{
    //设置表格控件
    tblwgtWorkerData->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tblwgtWorkerData->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    tblwgtWorkerData->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tblwgtWorkerData->verticalHeader()->setDefaultSectionSize(25);
    tblwgtWorkerData->setSelectionBehavior (QTableWidget ::SelectRows);
    //tblwgtWorkerData->setMinimumSize(400,300);

}
void LoginDialog::on_pbtnLogin_clicked()
{
    isUserManage = false;
    QString strWorkid = ledtWorkerID->text();
    QString strWorkPassword = ledtPassword->text();
    if(strWorkid == "" || strWorkPassword == ""){
        QMessageBox::warning(this,tr("警告"),tr("账户或密码为空，请输入"));
        return;
    }
    QJsonObject lognInfo;
    lognInfo.insert(WORKERID,QString::fromStdString(textEncry(strWorkid.toStdString().c_str())));
    lognInfo.insert(WORKERPASSWORD,QString::fromStdString(textEncry(strWorkPassword.toStdString().c_str())));
    emit sglOperate(Opt_Login,lognInfo);
}
void LoginDialog::on_pbtnUserManage_clicked()
{
    QString strWorkid = ledtWorkerID->text();
    QString strWorkPassword = ledtPassword->text();
    if(strWorkid == "" || strWorkPassword == ""){
        QMessageBox::warning(this,tr("警告"),tr("账户或密码为空，请输入"));
        return;
    }
    isUserManage = true;
    QJsonObject lognInfo;
    lognInfo.insert(WORKERID,QString::fromStdString(textEncry(strWorkid.toStdString().c_str())));
    lognInfo.insert(WORKERPASSWORD,QString::fromStdString(textEncry(strWorkPassword.toStdString().c_str())));
    emit sglOperate(Opt_Login,lognInfo);
}
void LoginDialog::on_pbtnLogout_clicked()
{
    emit sglLogout();
    stkwgt->setCurrentIndex(0);
}
void LoginDialog::on_pbtnRegister_clicked()
{
    QDialog dialog(this);
    QFormLayout form(&dialog);
    dialog.setWindowTitle(tr("用户注册"));

    QLineEdit *id = new QLineEdit(&dialog);
    id->setText(QString::fromStdString(textDecry(m_signUpInfo.value(WORKERID).toString().toStdString().c_str())));
    form.addRow(tr("工号: "), id);

    QLineEdit *name = new QLineEdit(&dialog);
    name->setText(QString::fromStdString(textDecry(m_signUpInfo.value(WORKERNAME).toString().toStdString().c_str())));
    form.addRow(tr("姓名: "), name);


    //只能创建比当前登录用户权级更低的账户
    QComboBox *level = new QComboBox(&dialog);
    if(CurrentLevel == WL_ROOT){
        level->addItem(mapWorkerLevelName[WL_SUPERADMIN], WL_SUPERADMIN);
        level->addItem(mapWorkerLevelName[WL_ADMIN], WL_ADMIN);
        level->addItem(mapWorkerLevelName[WL_OPERATOR], WL_OPERATOR);
    }else if(CurrentLevel == WL_SUPERADMIN){
        level->addItem(mapWorkerLevelName[WL_ADMIN], WL_ADMIN);
        level->addItem(mapWorkerLevelName[WL_OPERATOR], WL_OPERATOR);
    }else if(CurrentLevel == WL_ADMIN){
        level->addItem(mapWorkerLevelName[WL_OPERATOR], WL_OPERATOR);
    }
    level->setCurrentText(QString::number(m_signUpInfo.value(WORKERLEVEL).toInt()));
    form.addRow(tr("权级: "), level);

    QLineEdit *pwd = new QLineEdit(&dialog);
    pwd->setEchoMode(QLineEdit::Password);
    form.addRow(tr("密码: "), pwd);

    QLineEdit *pwdRepeat = new QLineEdit(&dialog);
    pwdRepeat->setEchoMode(QLineEdit::Password);
    form.addRow(tr("重复输入密码: "), pwdRepeat);

    // 添加确认，取消按钮
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);
    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    buttonBox.button(QDialogButtonBox::Cancel)->setText(tr("取消"));
    buttonBox.button(QDialogButtonBox::Ok)->setText(tr("确认"));

    // 运行对话框，并判断返回
    if (dialog.exec() == QDialog::Accepted) {
        QString strWorkid = id->text();
        QString strWorkPassword = pwd->text();
        QString strWorkName = name->text();
        WorkerLevel workLevel = level->itemData(level->currentIndex()).value<WorkerLevel>();
        m_signUpInfo.insert(WORKERID,QString::fromStdString(textEncry(strWorkid.toStdString().c_str())));
        m_signUpInfo.insert(WORKERNAME,QString::fromStdString(textEncry(strWorkName.toStdString().c_str())));
        m_signUpInfo.insert(WORKERLEVEL, workLevel);
        if(strWorkid.remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("工号为空!\n请重新填写"));
            on_pbtnRegister_clicked();
            return;
        }
        if(strWorkPassword.remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("密码为空!\n请重新填写"));
            on_pbtnRegister_clicked();
            return;
        }
        if(strWorkName.remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("姓名为空!\n请重新填写"));
            on_pbtnRegister_clicked();
            return;
        }
        if(pwd->text() == pwdRepeat->text()) {
            m_signUpInfo.insert(WORKERPASSWORD,QString::fromStdString(textEncry(strWorkPassword.toStdString().c_str())));
            emit sglOperate(Opt_Register,m_signUpInfo);
        } else {
            QMessageBox::warning(this,tr("警告"),tr("注册失败，密码两次的不一致!\n请重新填写"));
            on_pbtnRegister_clicked();
            return;
        }
    }
}
void LoginDialog::on_pbtnModifyPassword_clicked()
{
    if(CurrentLevel == WL_ROOT){
        QMessageBox::warning(this,tr("警告"),tr("root的信息不允许修改！！！"));
        return;
    }
    QDialog dialog(this);
    QFormLayout form(&dialog);
    dialog.setWindowTitle(tr("修改密码"));

    QLineEdit *pwd = new QLineEdit(&dialog);
    pwd->setEchoMode(QLineEdit::Password);
    form.addRow(tr("输入旧密码: "), pwd);

    QLineEdit *newPwd1 = new QLineEdit(&dialog);
    newPwd1->setEchoMode(QLineEdit::Password);
    form.addRow(tr("输入新密码: "), newPwd1);

    QLineEdit *newPwd2 = new QLineEdit(&dialog);
    newPwd2->setEchoMode(QLineEdit::Password);
    form.addRow(tr("再次输入新密码: "), newPwd2);


    // 添加确认，取消按钮
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);
    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    buttonBox.button(QDialogButtonBox::Cancel)->setText(tr("取消"));
    buttonBox.button(QDialogButtonBox::Ok)->setText(tr("确认"));

    QJsonObject editInfo;
    if (dialog.exec() == QDialog::Accepted) {
        if(pwd->text().remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("旧密码为空!\n请重新填写"));
            on_pbtnModifyPassword_clicked();
            return;
        }
        if(m_password != pwd->text()){
            QMessageBox::warning(this,tr("警告"),tr("旧密码错误!\n请重新填写"));
            on_pbtnModifyPassword_clicked();
            return;
        }
        if(newPwd1->text().remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("新密码为空!\n请重新填写"));
            on_pbtnModifyPassword_clicked();
            return;
        }
        if(newPwd1->text() != newPwd2->text()) {
           QMessageBox::warning(this,tr("警告"),tr("两次输入的新密码不一致"));
           on_pbtnModifyPassword_clicked();
           return;
        }

        QString strWorkid = lblWorkerID->text();
        QString strWorkPassword = newPwd1->text();
        editInfo.insert(WORKERID,QString::fromStdString(textEncry(strWorkid.toStdString().c_str())));
        editInfo.insert(WORKERPASSWORD,QString::fromStdString(textEncry(strWorkPassword.toStdString().c_str())));
        emit sglOperate(Opt_ModifyPwd,editInfo);
        m_password = newPwd1->text();
    }
}
void LoginDialog::on_pbtnModifyInfo_clicked()
{
    if(CurrentLevel == WL_ROOT){
        QMessageBox::warning(this,tr("警告"),tr("超级管理员的信息不允许修改！！！"));
        return;
    }
    QDialog dialog(this);
    QFormLayout form(&dialog);
    dialog.setWindowTitle(tr("修改信息"));

    QLineEdit *name = new QLineEdit(&dialog);
    name->setText(m_name);
    form.addRow(tr("姓名: "), name);

    QComboBox *level = new QComboBox(&dialog);
    level->addItem(mapWorkerLevelName[WL_ROOT], WL_ROOT);
    level->addItem(mapWorkerLevelName[WL_SUPERADMIN], WL_SUPERADMIN);
    level->addItem(mapWorkerLevelName[WL_ADMIN], WL_ADMIN);
    level->addItem(mapWorkerLevelName[WL_OPERATOR], WL_OPERATOR);
//    level->addItems(QStringList() << mapWorkerLevelName[WL_SUPERADMIN] << mapWorkerLevelName[WL_ADMIN] << mapWorkerLevelName[WL_OPERATOR]<< mapWorkerLevelName[WL_GUEST]);
    level->setCurrentText(mapWorkerLevelName[CurrentLevel]);
    level->setEnabled(false);
    form.addRow(tr("权级: "), level);

    // 添加确认，取消按钮
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);
    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    buttonBox.button(QDialogButtonBox::Cancel)->setText(tr("取消"));
    buttonBox.button(QDialogButtonBox::Ok)->setText(tr("确认"));

    QJsonObject editInfo;
    if (dialog.exec() == QDialog::Accepted) {
        QString strWorkid = lblWorkerID->text();
        QString strWorkName = name->text();
        WorkerLevel workLevel = level->itemData(level->currentIndex()).value<WorkerLevel>();
        if(strWorkName.remove(" ") == ""){
            QMessageBox::warning(this,tr("警告"),tr("姓名为空!\n请重新填写"));
            on_pbtnModifyInfo_clicked();
            return;
        }
        editInfo.insert(WORKERID,QString::fromStdString(textEncry(strWorkid.toStdString().c_str())));
        editInfo.insert(WORKERNAME,QString::fromStdString(textEncry(strWorkName.toStdString().c_str())));
        editInfo.insert(WORKERLEVEL,workLevel);
        emit sglOperate(Opt_ModifyInfo,editInfo);
    }
}
void LoginDialog::on_pbtnDelete_clicked()
{
    int row = tblwgtWorkerData->currentRow();
    if(row == -1){
        QMessageBox::warning(this,tr("警告"),tr("当前未选择账户"));
        return;
    }
    QMessageBox box(this);
    box.setWindowTitle(tr("警告"));
    box.setText(tr("确定要删除用户") + tblwgtWorkerData->item(row,0)->text() + "吗");
    box.setStandardButtons (QMessageBox::Ok|QMessageBox::Cancel);
    box.setButtonText (QMessageBox::Ok,QString(tr("确定")));
    box.setButtonText (QMessageBox::Cancel,QString(tr("取消")));
    if (box.exec() == QMessageBox::Cancel) {
        return;
    }
    QJsonObject deleteInfo;
    deleteInfo.insert(WORKERID,QString::fromStdString(textEncry(tblwgtWorkerData->item(row,0)->text().toStdString().c_str())));
    deleteInfo.insert(WORKERNAME,QString::fromStdString(textEncry(tblwgtWorkerData->item(row,1)->text().toStdString().c_str())));
    deleteInfo.insert(WORKERLEVEL,tblwgtWorkerData->item(row,2)->text().toInt());
    emit sglOperate(Opt_Delete,deleteInfo);
}
void LoginDialog::setControlStatus()
{
    //操作员账户不允许注册和删除
    pbtnRegister->setVisible(CurrentLevel >= WL_ADMIN);
    pbtnDelete->setVisible(CurrentLevel >= WL_ADMIN);

    //Root不允许修改和删除
    pbtnModifyInfo->setVisible(CurrentLevel != WL_ROOT);
    pbtnModifyPassword->setVisible(CurrentLevel != WL_ROOT);
}

void LoginDialog::onOperateResult(UserOptID optID, bool result, QJsonObject optObj)
{
    switch (optID) {
    case Opt_Login:
    {
       if(!result){
           QMessageBox::warning(this,tr("提示"),tr("用户名或密码错误"));
       }else{

           m_workID = QString::fromStdString(textDecry(optObj.value(WORKERID).toString().toStdString().c_str()));
           m_name = QString::fromStdString(textDecry(optObj.value(WORKERNAME).toString().toStdString().c_str()));
           m_password = QString::fromStdString(textDecry(optObj.value(WORKERPASSWORD).toString().toStdString().c_str()));
           CurrentLevel = (WorkerLevel)optObj.value(WORKERLEVEL).toInt();
            //根据level设置状态，要再level赋值后
           setControlStatus();
            //设置控件显示
           lblWorkerID->setText(m_workID);
           lblWorkerName->setText(m_name);
           lblWorkerLevel->setText(mapWorkerLevelName[CurrentLevel]);
            //是否进入用户管理界面
           if(!isUserManage){
              emit sglLoginSucceed();
           }else{
              stkwgt->setCurrentIndex(1);
           }
       }
    }
        break;
    case Opt_Register:
    {
        if(!result){
            QMessageBox::warning(this,tr("提示"),tr("用户注册失败"));
        }else{
            QMessageBox::warning(this,tr("提示"),tr("用户注册成功"));
        }
    }
        break;
    case Opt_ModifyPwd:
    {
        if(!result){
            QMessageBox::warning(this,tr("提示"),tr("修改密码失败"));
        }else{
            QMessageBox::warning(this,tr("提示"),tr("修改密码成功"));
            m_password = QString::fromStdString(textDecry(optObj.value(WORKERPASSWORD).toString().toStdString().c_str()));
        }
    }
        break;
    case Opt_ModifyInfo:
    {
        if(!result){
            QMessageBox::warning(this,tr("提示"),tr("修改信息失败"));
        }else{
            QMessageBox::warning(this,tr("提示"),tr("修改信息成功"));
            m_name = QString::fromStdString(textDecry(optObj.value(WORKERNAME).toString().toStdString().c_str()));
            lblWorkerName->setText(m_name);
        }
    }
        break;
    case Opt_Delete:
    {
        if(!result){
            QMessageBox::warning(this,tr("提示"),tr("删除用户失败"));
        }else{
            QMessageBox::warning(this,tr("提示"),tr("删除用户成功"));
        }
    }
        break;
    default:
        break;
    }
}

void LoginDialog::onAllUserShow(QJsonArray allUser)
{
    if(!isUserManage)
        return;
    //判断账户的level
    QJsonArray userShow;
    foreach(QJsonValue value, allUser){
        QJsonObject obj = value.toObject().value("data").toObject();
        if(obj.value(WORKERLEVEL).toInt() < CurrentLevel) {
            obj.insert(WORKERID,value.toObject().value(WORKERID));
            userShow.append(obj);
        }
    }
    //移除全部
    int rowCount = tblwgtWorkerData->rowCount();
    for (int i = 0; i< rowCount; i++) {
        tblwgtWorkerData->removeRow(0);
    }
    //显示level低的账户信息
    foreach(QJsonValue value, userShow){
        QJsonObject obj = value.toObject();
        tblwgtWorkerData->insertRow(tblwgtWorkerData->rowCount());
        QTableWidgetItem * item0 = new QTableWidgetItem(QString::fromStdString(textDecry(obj.value(WORKERID).toString().toStdString().c_str())));
        item0->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        tblwgtWorkerData->setItem(tblwgtWorkerData->rowCount()-1,0,item0);
        QTableWidgetItem * item1 = new QTableWidgetItem(QString::fromStdString(textDecry(obj.value(WORKERNAME).toString().toStdString().c_str())));
        item1->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        tblwgtWorkerData->setItem(tblwgtWorkerData->rowCount()-1,1,item1);
        QTableWidgetItem * item2 = new QTableWidgetItem(mapWorkerLevelName[(WorkerLevel)obj.value(WORKERLEVEL).toInt()]);
        item2->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        tblwgtWorkerData->setItem(tblwgtWorkerData->rowCount()-1,2,item2);
    }
}
void LoginDialog::keyPressEvent(QKeyEvent *event)
{
    if(stkwgt->currentIndex() == 0){
        switch (event->key()) {
            case Qt::Key_Escape:
                close();
                break;
            case Qt::Key_Return://注意和Qt::Key_Enter区分
                on_pbtnLogin_clicked();
                break;
            default:
                QWidget::keyPressEvent(event);
                break;
        }
    }
}
void LoginDialog::on_pbtnCancel_clicked()
{
    close();
}

std::string LoginDialog::textEncry(const char* strI)
{
    //字符串加密
    std::string strReturn = strI;
    int len = strlen(strReturn.c_str());
    for (int i = 0; i < len; i++)
    {
        strReturn[i] = strReturn[i] + i + 1;
    }
    return strReturn;
}

std::string LoginDialog::textDecry(const char* strI)
{
    //字符串解密
    std::string strReturn = strI;
    int len = strlen(strReturn.c_str());
    for (int i = 0; i < len; i++)
    {
        strReturn[i] = strReturn[i] - i - 1;
    }
    return strReturn;
}

